package com.healthy_software.controller;


import com.healthy_software.constant.JwtClaimsConstant;
import com.healthy_software.dto.UserWXLoginDTO;
import com.healthy_software.entity.User;
import com.healthy_software.properties.JwtProperties;
import com.healthy_software.result.Result;
import com.healthy_software.service.UserService;
import com.healthy_software.utils.JwtUtil;
import com.healthy_software.vo.UserLoginVO;
import com.healthy_software.vo.UserWXLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/user")
public class UserWXController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 微信登陆
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<UserWXLoginVO> login(@RequestBody UserWXLoginDTO userWXLoginDTO) {
        //微信登陆
        User user = userService.wxLogin(userWXLoginDTO);

        //为微信用户生成JWT令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserWXSecretKey(), jwtProperties.getUserWXTtl(), claims);

        UserWXLoginVO userWXLoginVO = UserWXLoginVO.builder().id(user.getId()).token(token).openid(user.getOpenid()).build();
        return Result.success(userWXLoginVO);
    }
}
